package org.yiming.tools.mqtt.client.command;

import lombok.RequiredArgsConstructor;
import org.yiming.tools.mqtt.client.ApplicationContext;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author renwenpeng
 * date  2022/3/25 4:37 下午
 */
@RequiredArgsConstructor
public class CommandDispatcher {
    private final ApplicationContext applicationContext;
    private final EmptyCommand emptyCommand = new EmptyCommand();

    public String execute(String cmdLine){
        Command command = null;
        String[] args = new String[0];
        if (cmdLine != null && !"".equals(cmdLine.trim())) {
            String[] split = cmdLine.split(" ");
            // 去掉空字符串，多个相连空字符串
            List<String> collect = Arrays.stream(split).filter(s -> !"".equals(s)).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                split = collect.toArray(new String[0]);
                command = applicationContext.getCommandMap().get(split[0].trim());
                args = new String[split.length - 1];
                System.arraycopy(split, 1, args, 0, split.length - 1);
            }
        }
        return Optional.ofNullable(command).orElse(emptyCommand).execute(args);
    }
}
